const db = require('../../db/index')
const { comparePassword } = require('../../utils/secret')

const checkRegisterSql = 'select * from ev_users where username = ?'
const addRegisterSqlStr = 'insert into ev_users set ?'
const checkLoginSqlStr = 'select * from ev_users where username = ?'

const isRegisterSql = (username) => {
    return new Promise((resolve, reject) => {
        db.query(checkRegisterSql, username, (err, results) => {
            if (err) return reject(err)
            if (results.length > 0) {
                resolve({
                    code: 0,
                    message: '用户名已经被占用,请重新输入'
                })
            } else {
                resolve({
                    code: 1,
                    message: '用户名可以使用'
                })
            }
        })
    })
}

const addRegisterSql = (user) => {
    return new Promise((resolve, reject) => {
        db.query(addRegisterSqlStr, user, (err, results) => {
            if (err) return reject(err)
            if (results.affectedRows === 1) {
                resolve({
                    code: 0,
                    message: '注册成功'
                })
            } else {
                resolve({
                    code: 1,
                    message: '注册失败'
                })
            }
        })
    })

}

const checkLoginSql = (username, password) => {
    return new Promise((resolve, reject) => {
        db.query(checkLoginSqlStr, [username], (err, results) => {
            if (err) return reject(err)
            if (results.length === 0) {
                resolve({
                    code: 1,
                    message: '用户名不存在'
                })
            } else {
                let user = results[0]
                if (comparePassword(password, user.password)) {
                    resolve({
                        code: 0,
                        message: '登录成功'
                    })
                } else {
                    resolve({
                        code: 1,
                        message: '密码错误'
                    })
                }
            }
        })
    })
}

module.exports = {
    isRegisterSql,
    addRegisterSql,
    checkLoginSql
}